package com.andy.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andy.dao.IExamScoreDAO;
import com.andy.dao.IExamUserDAO;
import com.andy.entity.ExamScore;
import com.andy.entity.ExamSubject;
import com.andy.entity.ExamUser;
import com.andy.vo.ExamScoreVO;
import com.andy.vo.ExamSubjectVO;
import com.andy.vo.ExamUserVO;

@Service
@Transactional
public class StudentService implements IStudentService {

	@Autowired
	private IExamUserDAO examUserDAO;
	
	@Autowired
	private IExamScoreDAO examScoreDAO;
	
	@Override
	public List<ExamSubjectVO> getSubjectList(ExamUserVO userVO) {
		List<ExamSubjectVO> resultList = new ArrayList<ExamSubjectVO>();
		// 读取所有科目
		ExamUser user = examUserDAO.get(userVO.getUserId());
		Collection<ExamSubject> subs = user.getExamSubjects();
		for (ExamSubject sub : subs) {
			// 
			ExamSubjectVO subVO = new ExamSubjectVO();
			BeanUtils.copyProperties(sub, subVO);
			
			// 读取对应科目的成绩
			ExamScore score = examScoreDAO.getScore(userVO.getUserId(), subVO.getSubId());
			if (score != null) {
				ExamScoreVO scoreVO = new ExamScoreVO();
				BeanUtils.copyProperties(score, scoreVO);
				
				// 计算剩余考试时间
				Calendar startTime = Calendar.getInstance();
				startTime.setTime(scoreVO.getExamTime());
				
				Calendar currentTime = Calendar.getInstance();
				currentTime.setTime(new Date());
				
				long startSecond = startTime.getTimeInMillis();
				long currentSecond = currentTime.getTimeInMillis();
				long totalSecond = sub.getTotalTime() * 60;
				scoreVO.setRemainingExamTime(totalSecond  - (currentSecond - startSecond) / 1000);
				
				subVO.setScore(scoreVO);
			}
			
			resultList.add(subVO);
		}
		return resultList;
	}

	@Override
	public ExamScoreVO getScoreById(Integer scoreId) {
		ExamScoreVO vo = examScoreDAO.getScoreById(scoreId);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		vo.setExamTimeString(df.format(vo.getExamTime()));
//		ExamScore score = examScoreDAO.get(scoreId);
//		if (score != null) {
//			ExamScoreVO scoreVO = new ExamScoreVO();
//			BeanUtils.copyProperties(score, scoreVO);
//			return scoreVO;
//		}
		return vo;
	}
	
}
